package IOStream_etc.BufferStream_etc;

import org.junit.Test;

import java.io.*;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/29 11:51
 * 说明：
 */

public class BufferStreamTest {

    /**
     * 使用 BufferedInputStream和BufferedOutputStream复制一张图片
     */
    @Test
    public void test1() {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            // 1. 创建相关File类的对象
            File srcFile = new File("playboy.jpg");
            File desFile = new File("playboy_copy1.jpg");
            // 2. 创建相关字节流、缓冲流
            FileInputStream fis = new FileInputStream(srcFile);
            FileOutputStream fos = new FileOutputStream(desFile, true);

            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            // 3. 数据的读入和写出
            byte[] buffer = new byte[1024];
            int len; // 记录每次读入到buffer中字节的个数
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 4. 关闭资源
            // 关外层流
            try {
                bos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                bis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 关内层流。由于外层流的关闭也会关闭内层流，因此内层流的关闭操作可以省去
//        fos.close();
//        fis.close();
        }
    }
}
